// searchpage.js
const app = getApp();
Page({
  data: {
    list: [1, 2, 3, 3, 3, 3, 3],
    totalHeaderHeightall: "",
    keyword: '',
    questions: [],
    page: 1,
    pageSize: 2,
    totalCount: 0,
    loading: false,
    noMoreData: false,
    showEmpty: true,
    // 答题相关数据
    userAnswers: {}, // 存储用户选择的答案
    showAnswers: {}, // 存储哪些题目显示了答案
    showAnalyses: {}, // 存储哪些题目显示了解析
    // 评论相关数据
    showPinglunModal: false, // 控制评论弹窗显示
    currentQuestionId: '', // 当前题目ID
    commentList: {}, // 评论列表，按题目ID存储
    commentLoading: {}, // 评论列表加载状态
    commentPage: 1, // 评论当前页码
    commentLimit: 10 // 评论每页数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.setData({
      totalHeaderHeightall: app.globalData?.totalHeaderHeight
    })
    this.initSystemInfo();
  },

  /**
   * 生命周期函数--监听页面渲染完成
   */
  onReady: function () {
    // 页面渲染完成后，获取自定义头部组件实例
    this.headerComponent = this.selectComponent('#customHeader');
  },

  /**
   * 初始化系统信息
   */
  initSystemInfo: function () {
    try {
      // 获取系统信息
      const systemInfo = wx.getSystemInfoSync();
      // 获取状态栏高度
      const statusBarHeight = systemInfo.statusBarHeight;

      // 获取胶囊按钮位置信息
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();

      // 计算导航栏高度
      const navBarHeight = statusBarHeight + (menuButtonInfo.bottom - menuButtonInfo.top);

      // 设置默认内容padding-top，确保内容不被头部遮挡
      const contentPaddingTop = navBarHeight + 20; // 额外加20rpx的边距

      this.setData({
        statusBarHeight: statusBarHeight,
        navBarHeight: navBarHeight,
        menuButtonWidth: menuButtonInfo.width,
        contentPaddingTop: contentPaddingTop
      });
    } catch (e) {
      console.error('获取系统信息失败:', e);
      // 降级处理，使用默认高度
      this.setData({
        statusBarHeight: 20,
        navBarHeight: 64,
        menuButtonWidth: 80,
        contentPaddingTop: 84
      });
    }
  },

  /**
   * 监听头部高度变化事件
   */
  onHeaderHeightChange: function (e) {
    const { totalHeight, statusBarHeight, headerHeight } = e.detail;

    // 更新页面数据
    this.setData({
      statusBarHeight: statusBarHeight,
      navBarHeight: totalHeight,
      contentPaddingTop: totalHeight + 20 // 额外加20rpx的边距
    });
  },

  searchbtn() {
    if (this.data.keyword) {
      // 重置分页信息，重新开始搜索
      this.setData({
        page: 1,
        questions: [],
        noMoreData: false,
        showEmpty: false
      });
      this.searchQuestions();
    } else {
      // 如果搜索词为空，清空结果
      this.setData({
        questions: [],
        totalCount: 0,
        showEmpty: false
      });
    }
  },
  /**
   * 输入框内容变化处理
   */
  onInputChange: function (e) {
    const keyword = e.detail.value.trim();
    this.setData({
      keyword: keyword
    });



    // // 清除之前的定时器
    // if (this.searchTimer) {
    //   clearTimeout(this.searchTimer);
    // }

    // // 设置新的定时器，实现防抖（500ms延迟）
    // this.searchTimer = setTimeout(() => {

    // }, 500);
  },

  /**
   * 清除输入框内容
   */
  onClearInput: function () {
    // 清除输入框内容
    this.setData({
      keyword: '',
      questions: [],
      totalCount: 0,
      showEmpty: false
    });

    // 清除之前的定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  /**
   * 搜索按钮点击或回车键触发搜索
   */
  onSearch: function () {
    const { keyword } = this.data;
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    // 重置分页信息，重新开始搜索
    this.setData({
      page: 1,
      questions: [],
      noMoreData: false,
      showEmpty: false
    });

    this.searchQuestions();
  },

  /**
   * 搜索题目接口调用
   */
  searchQuestions: function () {
    const { keyword, page, pageSize, loading, noMoreData } = this.data;

    if (loading || noMoreData) return;

    this.setData({ loading: true });

    wx.showLoading({
      title: '搜索中...',
    });

    // 调用搜索接口
    wx.request({
      url: app.globalData?.baseUrl + '/frontend/searchQuestions',
      method: 'GET',
      data: {
        keyword: keyword,
        page: page,
        pageSize: pageSize
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data?.code === 200) {
          const rawData = res.data.data.data || [];
          const totalCount = res.data.data?.total || 0;

          // 处理数据，解析content中的题目内容
          const newQuestions = rawData.map(item => {
            try {
              // 获取题目类型文本
              item.isopen = false;
              const getQuestionTypeText = (type) => {
                const typeMap = {
                  0: '选择题',
                  1: '多项选择题',
                  2: '填空题',
                  3: '判断题',
                  4: '问答题',
                  5: '名词解释题',
                  6: '论述题'
                };
                return typeMap[type] || '其他题型';
              };

              // 先尝试解析content字段获取选项数据，参考dati页面的实现
              let options = [];

              // 首先尝试从item.question中获取数据（新格式）
              const questionData = item.question || item;

              try {
                // 尝试解析content字段获取选项数据
                if (questionData.content && typeof questionData.content === 'string') {
                  const contentObj = JSON.parse(questionData.content);
                  if (contentObj.options && Array.isArray(contentObj.options)) {
                    options = contentObj.options; // 保留完整的选项对象，包含key和content
                  }
                }
              } catch (e) {
                console.error('解析题目content字段失败:', e);
              }

              // 如果选项为空或格式不正确，尝试从其他字段获取选项数据
              if (options.length === 0 && questionData.options) {
                try {
                  // 尝试解析options字段
                  if (typeof questionData.options === 'string') {
                    const optionsData = JSON.parse(questionData.options);
                    if (Array.isArray(optionsData)) {
                      options = optionsData;
                    }
                  } else if (Array.isArray(questionData.options)) {
                    options = questionData.options;
                  }
                } catch (e) {
                  console.error('解析options字段失败:', e);
                }
              }

              // 确保选项有正确的key和content字段格式
              options = options.map((option, index) => {
                if (typeof option === 'string') {
                  // 如果选项是字符串，转换为对象格式
                  return {
                    key: String.fromCharCode(65 + index), // A, B, C, D...
                    content: option
                  };
                } else if (option && typeof option === 'object') {
                  // 如果选项是对象，确保有key和content字段
                  return {
                    key: option.key || String.fromCharCode(65 + index),
                    content: option.content || option.text || option.value || ''
                  };
                }
                return option;
              });

              return {
                ...item,
                title: item.question?.question_name || item.question_name || '暂无题目内容',
                options: options,
                answer: item.question?.right_key || item.right_key || '',
                analysis: item.question?.explains || item.explains || '暂无解析',
                type: item.question?.question_type || item.question_type,
                typeText: getQuestionTypeText(item.question?.question_type || item.question_type)
              };
            } catch (error) {
              console.error('解析题目内容失败:', error);
              return {
                ...item,
                title: item.question?.question_name || item.question_name || '题目内容解析失败',
                options: [],
                answer: item.question?.right_key || item.right_key || '',
                analysis: '题目解析失败',
                type: item.question?.question_type || item.question_type,
                typeText: '未知题型'
              };
            }
          });

          // 如果是第一页且没有数据，显示空状态
          if (page === 1 && newQuestions.length === 0) {
            this.setData({
              showEmpty: true,
              totalCount: 0
            });
          } else {
            // 合并数据
            this.setData({
              questions: page === 1 ? newQuestions : [...this.data.questions, ...newQuestions],
              totalCount: totalCount,
              showEmpty: false,
              noMoreData: this.data.questions.length + newQuestions.length >= totalCount,
              // 第一页时重置答题状态
              userAnswers: page === 1 ? {} : this.data.userAnswers,
              showAnswers: page === 1 ? {} : this.data.showAnswers,
              showAnalyses: page === 1 ? {} : this.data.showAnalyses
            });
          }
        } else {
          wx.showToast({
            title: res.data?.msg || '搜索失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('搜索接口调用失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
        wx.hideLoading();
      }
    });
  },

  /**
   * 加载更多数据
   */
  loadMore: function () {
    if (!this.data.loading && !this.data.noMoreData) {
      this.setData({
        page: this.data.page + 1
      });
      this.searchQuestions();
    }
  },

  /**
   * 选项点击事件
   */
  onOptionTap: function (e) {
    const { questionId, optionKey } = e.currentTarget.dataset;
    const { userAnswers, showAnswers } = this.data;

    // 如果已经显示答案，不允许再次选择
    if (showAnswers[questionId]) return;

    // 更新用户答案
    userAnswers[questionId] = optionKey;

    // 显示答案
    showAnswers[questionId] = true;

    this.setData({
      userAnswers: { ...userAnswers },
      showAnswers: { ...showAnswers }
    });
  },

  /**
   * 查看解析
   */
  nextQuestion: function (e) {
    const questionId = e.currentTarget.dataset.id;
    const { showAnalyses } = this.data;
    let chackindex = -1

    // 切换解析显示状态
    showAnalyses[questionId] = !showAnalyses[questionId];
    console.log(showAnalyses[questionId])
    if (showAnalyses[questionId]) {
      this.loadCommentList(questionId);
    }
    this.setData({
      currentQuestionId: questionId,
      showAnalyses: { ...showAnalyses }
    });
  },

  /**
   * 重新答题
   */
  retryQuestion: function (e) {
    const questionId = e.currentTarget.dataset.id;
    const { userAnswers, showAnswers, showAnalyses } = this.data;

    // 清除用户答案和显示状态
    delete userAnswers[questionId];
    delete showAnswers[questionId];
    delete showAnalyses[questionId];

    this.setData({
      userAnswers: { ...userAnswers },
      showAnswers: { ...showAnswers },
      showAnalyses: { ...showAnalyses }
    });
  },

  /**
   * 热门标签点击事件
   */
  onHotTagTap: function (e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword: keyword,
      // 重置答题状态
      userAnswers: {},
      showAnswers: {},
      showAnalyses: {}
    });
    this.onSearch();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 清除定时器，避免内存泄漏
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  // 时间格式化函数
  formatTime: function (timestamp) {
    if (!timestamp) return '';

    // 如果是时间戳格式（秒级或毫秒级）
    if (typeof timestamp === 'number' || /^\d+$/.test(timestamp)) {
      // 判断是秒级时间戳还是毫秒级时间戳
      let date;
      if (timestamp > 1000000000000) {
        // 毫秒级时间戳
        date = new Date(parseInt(timestamp));
      } else {
        // 秒级时间戳
        date = new Date(parseInt(timestamp) * 1000);
      }

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 如果是字符串格式，尝试直接返回
    if (typeof timestamp === 'string') {
      // 如果是ISO格式的时间字符串
      if (timestamp.includes('T') && timestamp.includes('Z')) {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 如果已经是格式化的时间字符串，直接返回
      if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(timestamp)) {
        return timestamp;
      }
    }

    // 其他情况返回原始值
    return timestamp;
  },

  // 加载评论列表
  loadCommentList: function (questionId) {
    const that = this;
    const { commentPage, commentLimit } = this.data;
    console.log(questionId)
    if (!questionId) {
      return;
    }

    // 设置加载状态
    const newCommentLoading = { ...this.data.commentLoading };
    newCommentLoading[questionId] = true;
    this.setData({
      commentLoading: newCommentLoading
    });

    try {
      // 调用API获取评论列表
      app.api.getCommentList({
        questionId: questionId,
        page: commentPage,
        limit: commentLimit
      }).then(res => {
        if (res && res.code === 200 && res.data) {
          const commentData = res.data;

          // 格式化评论数据
          const formattedComments = commentData.data.map(comment => ({
            id: comment.id,
            content: comment.content,
            likeCount: comment.like_count || 0,
            createTime: that.formatTime(comment.created_at),
            user: comment.user || {
              id: 0,
              nickname: '匿名用户',
              avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
            }
          }));

          // 更新对应题目的评论列表
          // const newCommentList = { ...that.data.commentList };
          // newCommentList[questionId] = formattedComments;

          let newarray = this.data.questions.map((item, index) => {
            console.log(item.id)
            console.log(this.data.currentQuestionId)
            console.log(item.id == this.data.currentQuestionId)
            if (item.id == this.data.currentQuestionId) {
              item.commentList = formattedComments
            }
            return item
          })
          console.log(newarray)
          that.setData({
            questions: JSON.parse(JSON.stringify(newarray)),
            // commentList: newCommentList
          });
        }

        // 无论成功失败，都设置加载状态为false
        const updatedCommentLoading = { ...that.data.commentLoading };
        updatedCommentLoading[questionId] = false;
        that.setData({
          commentLoading: updatedCommentLoading
        });
      }).catch(err => {
        console.error('加载评论列表失败:', err);

        // 加载失败，设置默认评论数据
        that.setDefaultCommentData(questionId);

        // 设置加载状态为false
        const updatedCommentLoading = { ...that.data.commentLoading };
        updatedCommentLoading[questionId] = false;
        that.setData({
          commentLoading: updatedCommentLoading
        });
      });
    } catch (error) {
      console.error('加载评论出错:', error);
      // 设置加载状态为false
      const updatedCommentLoading = { ...this.data.commentLoading };
      updatedCommentLoading[questionId] = false;
      this.setData({
        commentLoading: updatedCommentLoading
      });
    }
  },

  // 设置默认评论数据
  setDefaultCommentData: function (questionId) {
    const defaultComments = [
      {
        id: 1,
        content: '这道题很有代表性，考察了核心知识点',
        likeCount: 5,
        createTime: '2024-01-15 10:30:00',
        user: {
          id: 1,
          nickname: '学习达人',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      },
      {
        id: 2,
        content: '选项分析很到位，收获很大',
        likeCount: 3,
        createTime: '2024-01-14 15:20:00',
        user: {
          id: 2,
          nickname: '学霸小张',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      }
    ];

    const newCommentList = { ...this.data.commentList };
    newCommentList[questionId] = defaultComments;

    this.setData({
      commentList: newCommentList
    });
  },

  // 打开评论弹窗
  openPinglunModal: function (e) {
    const questionId = e.currentTarget.dataset.questionId;
    this.setData({
      showPinglunModal: true,
      currentQuestionId: questionId
    });

    // 加载该题目的评论列表
    this.loadCommentList(questionId);
  },

  // 关闭评论弹窗
  closePinglunModal: function () {
    this.setData({
      showPinglunModal: false
    });
  },

  changeoobj(e) {
    console.log(e.currentTarget.dataset.id)
    let newobj = this.data.questions.map((item, index) => {
      if (item.id == e.currentTarget.dataset.id) {
        item.isopen = !item.isopen
      }
      return item
    })
    this.setData({
      questions: JSON.parse(JSON.stringify(newobj))
    })
  },
  // 处理评论提交
  handlePinglunSubmit: function (e) {
    const { content, commentId } = e.detail;
    console.log('收到评论内容:', content, '评论ID:', commentId);

    // 评论组件已经调用了API，这里只需要重新加载评论列表显示最新评论
    this.loadCommentList(this.data.currentQuestionId);
  },

  // 点赞评论
  likeComment: function (e) {
    const { commentId, questionId } = e.currentTarget.dataset;
    const that = this;

    if (!commentId || !questionId) {
      return;
    }

    try {
      // 调用API点赞评论
      app.api.likeComment({
        commentId: commentId
      }).then(res => {
        if (res && res.code === 200) {
          // 点赞成功，更新本地评论列表
          const { commentList } = that.data;
          const questionComments = commentList[questionId] || [];
          const updatedComments = questionComments.map(comment => {
            if (comment.id === commentId) {
              return {
                ...comment,
                likeCount: comment.likeCount + 1
              };
            }
            return comment;
          });

          const newCommentList = { ...commentList };
          newCommentList[questionId] = updatedComments;

          that.setData({
            commentList: newCommentList
          });

          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '点赞失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('点赞评论失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      });
    } catch (error) {
      console.error('点赞出错:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
});
